package com.va.feedback.component;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.RelativeLayout;

import com.va.feedback.FeedbackItemConstants;

public class RatingFeedback extends AbstractFeedback {

	private EditText textWidget;
	private RatingBar ratingWidget;

	/**
	 * Constructor for RatingFeedback
	 * @param context context of the parent
	 */
	public RatingFeedback(Context context) {
		super(context);

		addQuestionWidget();
		
		addAnswerComponent();

		FeedbackItemConstants.RATING_TYPE_ID_CURRENT++;
	}
	
	/**
	 * Sets the properties
	 */
	public void setComponentProperty(String type, Object value) {
		if (FeedbackItemConstants.PROPERTY_QUESTION.equals(type)) {
			String question = (String) value;
			questionWidget.setText(question);
		} else if (FeedbackItemConstants.PROPERTY_TEXT_HINT.equals(type)) {
			String textHint = (String) value;
			textWidget.setHint(textHint);
		}
	}
	
	/**
	 * Adds the component which captures the user response to the question widget
	 */
	protected void addAnswerComponent() {
		ratingWidget = new RatingBar(context);
		RelativeLayout.LayoutParams ratingWidgetLayout = new RelativeLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		ratingWidget.setId(FeedbackItemConstants.RATING_TYPE_ID_CURRENT);
		ratingWidget.setNumStars(5);
		ratingWidgetLayout.addRule(RelativeLayout.BELOW, 1);
		this.addView(ratingWidget, ratingWidgetLayout);
	}
	
	/**
	 * Returns the response in the form of a JSONObject
	 * The response is : {'qid': qid, 'answer': rating}
	 */
	public JSONObject getFeedback() throws JSONException {
		float rating = ratingWidget.getRating();
		if (rating == 0)
			return null;
		JSONObject object = new JSONObject();
		object.put("qid", qid);
		object.put("answer", rating);
		return object;
	}

}
